<template>
  <el-breadcrumb separator="/" style="margin: 20px 20px 20px 20px">
    <el-breadcrumb-item :to="'/'">首页</el-breadcrumb-item>
    <el-breadcrumb-item>协同指挥决策</el-breadcrumb-item>
    <el-breadcrumb-item>多部门协同处置</el-breadcrumb-item>
    <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
  </el-breadcrumb>
  <div class="content-body">
    <el-form
      ref="formRef"
      :model="formData"
      autocomplete="off"
      :rules="rules"
      label-position="right"
      label-width="135px"
    >
      <!-- 已完结不进行编辑 -->
      <template v-if="route.query.status != 30">
        <div class="row-title">
          <div class="title-circle"></div>
          <div class="title">
            <div class="title-text">事件处置</div>
            <div class="title-content">
              {{
                `${new Date()
                  .toLocaleString("zh-CN", { hour12: false })
                  .replace(/\//g, "-")
                  .slice(0, -3)} ${creator.name}`
              }}
              处置
            </div>
          </div>
        </div>
        <div class="row-content row-content-border">
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="处置过程：" prop="handleProcess">
                <el-input
                  v-model="formData.handleProcess"
                  maxlength="500"
                  show-word-limit
                  :rows="3"
                  type="textarea"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="协同人：" prop="personId">
                <el-select
                  v-model="formData.personId"
                  filterable
                  multiple
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in userData"
                    :key="item.userId"
                    :label="item.name"
                    :value="item.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处置结果：" prop="handleResult">
                <el-radio-group
                  v-model="formData.handleResult"
                  label="label position"
                >
                  <el-radio-button :label="1">已完结</el-radio-button>
                  <el-radio-button :label="2">处置中</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="附件上传：" prop="files">
                <upload-files
                  :limit="10"
                  v-model="formData.files"
                  :formRef="formRef"
                  formKey="files"
                  :accept="[
                    'jpg',
                    'jpeg',
                    'png',
                    'gif',
                    'bmp',
                    'svg',
                    'doc',
                    'docx',
                  ]"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </template>

      <template v-for="(item, i) in infoData.dispositionList" :key="i">
        <div class="row-title">
          <div class="title-circle"></div>
          <div class="title">
            <div class="title-text">事件处置</div>
            <div class="title-content">
              {{ `${item.createTime} ${item.creator.name}` }} 处置
            </div>
          </div>
        </div>
        <div class="row-content row-content-border">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="处置过程：">
                <span>{{ item.handleProcess }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处置人：">
                <span>{{ item.creator.name }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="协同人：">
                <span v-for="(item2, i) in item.person || []" :key="i"
                  >{{ item2.name }};</span
                >
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="处置结果：">
                <span>{{ item.handleResult == 1 ? "已完结" : "处置中" }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="附件：">
                <upload-files
                  disabled
                  v-model="item.files"
                  :accept="[
                    'jpg',
                    'jpeg',
                    'png',
                    'gif',
                    'bmp',
                    'svg',
                    'doc',
                    'docx',
                  ]"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- </div> -->
      </template>
      <div class="row-title">
        <div class="title-circle"></div>
        <div class="title">
          <div class="title-text">事件接收</div>
          <div class="title-content">
            {{
              `${infoData.receiveObj.createTime} ${infoData.receiveObj?.creator?.name}`
            }}
            接收
          </div>
        </div>
      </div>
      <div class="row-content row-content-border">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="接收人：">
              <span>{{ infoData.receiveObj?.creator?.name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收时间：">
              <span>{{ infoData.receiveObj.createTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="row-title">
        <div class="title-circle"></div>
        <div class="title">
          <div class="title-text">事件响应并下发</div>
          <div class="title-content">
            {{
              `${infoData.approve.createTime} ${infoData.approve.creator?.name}`
            }}
            分析并响应
          </div>
        </div>
      </div>
      <div class="row-content row-content-border">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="事件级别：">
              <span>{{
                handleTranslate(eventLevel, infoData.approve.eventLevel)
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区域处置单位：">
              <span>{{ infoData.approve?.processGroup?.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="附件上传：">
              <upload-files
                disabled
                v-model="infoData.approve.files"
                :accept="[
                  'jpg',
                  'jpeg',
                  'png',
                  'gif',
                  'bmp',
                  'svg',
                  'doc',
                  'docx',
                ]"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="row-title">
        <div class="title-circle" style="background-color: #ddd"></div>
        <div class="title">
          <div class="title-text">事件上报</div>
          <div class="title-content">
            {{
              `${infoData.report.createTime} ${infoData.report.creator?.name}`
            }}
            上报
          </div>
        </div>
      </div>
      <div class="row-content">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="发生区域：">
              <span>{{
                handleTranslate(platformList, infoData.report.terminal)
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="事件地点：">
              <span>{{ infoData.report.location }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="事件类型：">
              <span>{{
                findTypeName(eventTypes, infoData.report.eventTypeId)?.join(
                  " - "
                )
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="事件描述：">
              <span>{{ infoData.report.description }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="发现时间：">
              <span>{{ infoData.report.eventTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="后果/影响：">
              <span>{{
                handleTranslate(consequence, infoData.report.result)
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="事件级别：">
              <span>{{
                handleTranslate(eventLevel, infoData.report.eventLevel)
              }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="区域处置单位：">
              <span>{{ infoData.report?.processGroup?.name }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="附件上传：">
              <upload-files
                disabled
                v-model="infoData.report.files"
                :accept="[
                  'jpg',
                  'jpeg',
                  'png',
                  'gif',
                  'bmp',
                  'svg',
                  'doc',
                  'docx',
                ]"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="bottom-btn">
        <el-button plain @click="router.go(-1)">取消</el-button>
        <el-button
          v-if="route.query.status != 30"
          type="primary"
          style="margin-left: 50px"
          @click="handleEventDisposition"
          :loading="loadingBtn"
          >确定</el-button
        >
      </div>
    </el-form>
  </div>
</template>
<script setup>
import {
  ref,
  reactive,
  onBeforeMount,
  defineProps,
  computed,
  watch,
} from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import {
  eventReport,
  reportInfo,
  approveInfo,
  getTree,
  getConsequence,
} from "@/api/collaborativeCommand/eventEscalation";
import {
  eventDisposition,
  dispositionInfo,
  receiveInfo,
  getUser,
} from "@/api/collaborativeCommand/collaborativeDisposal";
import { getResource } from "@/api/resource";
import uploadFiles from "@/components/UploadFiles/index.vue";
import { handleTranslate, findTypeName } from "../components/common.js";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

const formData = reactive({
  files: [],
  personId: [],
}); //表单数据
const formRef = ref(); //表单ref
const infoData = reactive({
  //页面展示信息
  report: {}, //上报信息
  approve: {}, //响应信息
  receiveObj: {}, //接收信息
  dispositionList: [], //处置信息
});
const userData = ref([]);
const rules = reactive({
  handleProcess: [
    { required: true, message: "请输入处置过程", trigger: "blur" },
  ],
  personId: [{ required: true, message: "请选择协同人", trigger: "change" }],
  handleResult: [
    { required: true, message: "请选择处置结果", trigger: "change" },
  ],
  files: [{ required: true, message: "请上传附件", trigger: "change" }],
});
const loadingBtn = ref(false);

// 数据字典
const platformList = ref([]); //发生区域
const eventTypes = ref([]); //事件类型
const eventUrgency = ref([]); //事件紧急程度
const consequence = ref([]); //后果/影响
const eventLevel = ref([]); //事件级别

// 用户信息
const store = useStore();
const userInfo = computed(() => store.state.user.userInfo);
const creator = reactive({
  id: userInfo.value.userId,
  name: userInfo.value.name,
  organId: userInfo.value.organId,
  organName: userInfo.value.organName,
});

// 面包屑
const breadcrumbName = computed(() => {
  const { status } = route.query;
  if (status == 21 || status == 22) {
    return "事件处置";
  } else if (status == 30) {
    return "查看完结事件处置";
  }
});
/**
 * 事件处置提交
 */
const handleEventDisposition = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const person = [];
      formData.personId.forEach((item) => {
        const obj = userData.value.find((item2) => item2.userId == item);
        if (typeof obj !== "undefined") {
          person.push({
            id: obj?.userId,
            name: obj?.name,
          });
        }
      });
      const data = {
        ...formData,
        person,
        creator,
        eventReportId: route.query.id,
      };
      delete data.personId;
      loadingBtn.value = true;
      eventDisposition(data)
        .then((res) => {
          if (res.code === "1") {
            router.go(-1);
          } else {
            ElMessage.error(res.message);
          }
          loadingBtn.value = false;
        })
        .catch((err) => {
          loadingBtn.value = false;
          ElMessage.error(err.message);
        });
    }
  });
};
/**
 * 获取事件上报信息  响应信息  接收信息  处置信息
 */
const loadData = () => {
  Promise.all([
    reportInfo(route.query.id),
    approveInfo({ id: route.query.id }),
    receiveInfo({ id: route.query.id }),
    dispositionInfo({ id: route.query.id }),
  ])
    .then(([res1, res2, res3, res4]) => {
      if (
        res1.code == 1 &&
        res2.code == 1 &&
        res3.code == 1 &&
        res4.code == 1
      ) {
        infoData.report = res1.data || {};
        infoData.approve =
          res2.data.filter((item) => item.status == 20)[0] || {};
        infoData.receiveObj = res3.data[0] || {};
        infoData.dispositionList = res4.data?.reverse() || [];
      }
    })
    .catch((err) => {
      ElMessage.error(err.message || "数据获取失败");
    });
};
// 获取协同人
const handleUser = () => {
  getUser()
    .then((res) => {
      if (res.code == 1) {
        userData.value = res.data;
      }
    })
    .catch((err) => {
      ElMessage.error(err.message || "数据获取失败");
    });
};
/**
 * 加载数据字典
 */
const loadDict = () => {
  Promise.all([
    getResource("terminals"),
    getResource("event_rules_exigency_level"),
    getResource("event_rules_event_level"),
    getTree(),
    getConsequence({ enabled: 1 }),
  ]).then(([res1, res2, res3, res4, res5]) => {
    platformList.value = res1.data.properties.meta;
    eventUrgency.value = res2.data.properties.meta;
    eventLevel.value = res3.data.properties.meta;
    eventTypes.value = res4.data;
    consequence.value = res5.data?.map((item) => {
      return {
        value: item.id,
        label: item.result,
      };
    });
  });
};
const initData = () => {
  loadData();
  handleUser();
  loadDict();
};
onBeforeMount(initData);
</script>

<style lang="less" scoped>
.content-body {
  padding: 0 60px;
  background-color: white;
  min-height: 100%;
  height: auto;
  margin-left: 10px;

  .row-title {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding-top: 20px;

    .title-circle {
      width: 40px;
      height: 40px;
      border-radius: 40px;
      background-color: #2f7df1;
    }

    .title {
      margin-left: 10px;

      .title-text {
        color: #353a42;
        font-size: 16px;
        margin: 10px 0;
        font-weight: bold;
      }

      .title-content {
        font-size: 12px;
        color: #999;
      }
    }
  }

  .row-content {
    padding-top: 20px;
    margin-left: 20px;
  }

  .row-content-border {
    border-left: 1px solid #ddd;
  }

  .bottom-btn {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 30px;
    padding-bottom: 30px;
    position: sticky;
    bottom: 0px;
    background: #fff;
  }
}
</style>
